﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Baosight.ZNH.ZMCommon;
using Baosight.ZNH.ZMCommon.Validators;
using Baosight.Platform.Core;
using Telerik.Windows.Controls.GridView;
using Baosight.Platform.Core.UI.Controls;
using Telerik.Windows.Controls;
using Baosight.Platform.Core.ServiceModel;
using Baosight.ZNH.ZMCommon.ChildWindows;

namespace Baosight.ZNH.ZMCM.UI.ChildWindows
{
    public partial class ImportMaterialInsert : EFViewCmes
    {
        public ImportMaterialInsert(string dialogType)
        {
            InitializeComponent();
            Init(dialogType);
        }

        /// <summary>
        /// 初始化页面数据
        /// </summary>
        private void Init(string type)
        {
            type = type == null ? "insert" : type.ToLower();

            switch (type)
            {
                case "insert":
                    
                    base.Mode = OperationMode.Insert;
                    break;
                case "update":
                    base.Mode = OperationMode.Update;
                    
                    break;
                case "detail":
                    //this.Commit.Visibility = Visibility.Collapsed;
                    //BaseTools.EFDataFieldNotEnabled(this.spWindows.GetChildObjects<EFDataField>(null, true));
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// “下一步(填写物资资料)”按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Next_Click(object sender, RoutedEventArgs e)
        {
            if (InsertGrid.ValidateField())
            {
                ValidateCode();
            }
        }

        private void Last_Click(object sender, RoutedEventArgs e)
        {
            //显示上帧页面
            this.InsertGrid.Visibility = Visibility.Visible;//主表录入
            this.fdImportType.IsEnabled = false;
            this.Next.Visibility = Visibility.Visible;  //下一步按钮
            this.Cancel.Visibility = Visibility.Visible; //关闭按钮

            //隐藏下帧页面
            this.RESULT.Visibility = Visibility.Collapsed;
            this.DETAILS.Visibility = Visibility.Collapsed;

            this.Save.Visibility = Visibility.Collapsed;
            this.Clear.Visibility = Visibility.Collapsed;
            this.Last.Visibility = Visibility.Collapsed;
            this.Commit.Visibility = Visibility.Collapsed;
            this.Return.Visibility = Visibility.Collapsed;
        }

        /// <summary>
        /// “关闭”按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            CmesWindows _window = this.Parent as CmesWindows;
            _window.DialogResult = false;
            _window.Close();
        }

        /// <summary>
        /// “删除”链接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeleteButton_Click(object sender, RoutedEventArgs e)
        {
            base.TempHyperlink = sender as HyperlinkButton;
            DialogParameters param = this.ModelDialogParameters("Confirm", "确定删除所选择的记录？");
            param.Closed = DeleteConfirmClosed;
            EFWindow.Confirm(param);
        }

        /// <summary>
        /// 点击确认按钮执行事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeleteConfirmClosed(object sender, WindowClosedEventArgs e)
        {
            if (e.DialogResult == null)
            {
                return;
            }
            if (e.DialogResult.Value)
            {
                EIRow row = (base.TempHyperlink.ParentOfType<GridViewRow>().Item as UIBaseEntity).GetEIRow();
                this.sub_grid.EIBlock.Rows.Remove(row);
            }
        }

        /// <summary>
        /// “保存”按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Save_Click(object sender, RoutedEventArgs e)
        {
            //按钮不可用，防止双击
            Button button = sender as Button;
            button.IsEnabled = false;
            TempButton = button;


            bool result = ValidateImportType();
            if (!result)
            {
                return;
            }
            //ValidatorManager自定义的校验方法
            ValidatorManager group = this.GetChildObject<ValidatorManager>(null);
            if (group != null)
            {
                result = group.IsValidSucces;
            }

            bool _validateField = result;//确定前的效验

            if (!_validateField)
            {
                this.ValidateMessagePopup();//弹出提示信息
                this.TempButtonOpen(true);//确定按钮生效
            }
            else
            {
                String code =  this.fdMaterialCode.Value.ToString();
                int count = this.sub_grid.EIBlock.GetRowCount();
                foreach (EIRow code_row in this.sub_grid.EIBlock.GetRows())
                {
                    if (code.Equals(code_row["fdMaterialCode"].ToString()))
                    {
                        base.OpenEFWindowAlert("物资编码重复，请重新选择物资编码！", true);
                        this.TempButtonOpen(true);
                        return;
                    }
                }

                EIRow row = new EIRow();
                foreach (var _field in this.DETAILS.GetChildObjects<EFDataField>(null, true))
                {
                    row.Add(_field.eBindingName, _field.Value);
                }
                this.sub_grid.EIBlock.AddRow(row);

                //保存后，清空文本框信息
                foreach (var field in this.DETAILS.GetChildObjects<EFDataField>(null, true))
                {
                    field.SetDataValue("");
                    if (field.Name.Equals("fdMaterialCode"))//如果是公共选择则重新获得对象
                    {
                        CmesCustomView picker = field.Content as CmesCustomView;
                        picker.ItemObject = "";
                    }
                }
                if (group != null)
                {
                    group.InValidateAll();
                }

                this.TempButtonOpen(true);//确定按钮生效
            }

        }

        /// <summary>
        /// “清空”按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Clear_Click(object sender, RoutedEventArgs e) 
        {
            foreach (var field in this.DETAILS.GetChildObjects<EFDataField>(null, true))
            {
                field.SetDataValue("");
                if (field.Name.Equals("fdMaterialCode"))//如果是公共选择则重新获得对象
                {
                    CmesCustomView picker = field.Content as CmesCustomView;
                    picker.ItemObject = "";
                }

            }
            //清除列表值得时候设置校验为无效
            ValidatorManager group = this.GetChildObject<ValidatorManager>(null);
            if (group != null)
            {
                group.InValidateAll();
            }
        }

        /// <summary>
        /// "确定"按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Commit_Click(object sender, RoutedEventArgs e)
        {
            //按钮不可用，防止双击
            Button button = sender as Button;
            button.IsEnabled = false;
            TempButton = button;

            if (this.sub_grid.EIBlock.GetRowCount() > 0)
            {
                EIInfo eiInfo = new EIInfo();
                eiInfo.Set("service", "ZMCMB2");
                eiInfo.Set("method", "insert");

                //主表新增block
                this.BaseBlock(eiInfo);
                //列表新增下一步block
                this.SubBlock(eiInfo);

                HttpServiceAgent agent = new HttpServiceAgent();
                agent.CallService(eiInfo, OnDoWorkCompleted);
            }
            else 
            {
                base.OpenEFWindowAlert("请添加物资明细信息！", true);
                this.TempButtonOpen(true);
                return;
            }
           
        }

        /// <summary>
        /// 新增后的回调方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnDoWorkCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            EIInfo inInfo = e.EIInfo;
            if (inInfo.Status == -1)
            {
                this.TempButtonOpen(true);
                this.OnCommitMessagePopup(inInfo);//操作失败，消息提醒
            }
            else
            {
                EFWindow window = this.Parent as EFWindow;
                window.DialogResult = true;
                window.Close();
            }
        }

        /// <summary>
        /// 将新增页面中的录入信息组织成一个block
        /// </summary>
        /// <param name="eiInfo"></param>
        private void BaseBlock(EIInfo eiInfo)
        {
            EFViewCmesProperty _view = new EFViewCmesProperty();
            _view.DataFields = this.InsertGrid.GetChildObjects<EFDataField>(null, true);
            base.ViewProperty = _view;
            
            EIBlock baseBlock = new EIBlock("baseBlock");
            baseBlock.SetColumns(base.GetDataFieldColumns("baseBlock"));
            baseBlock.AddRow(base.GetDataFieldValues("baseBlock"));
            eiInfo.AddBlock(baseBlock);
        }

        /// <summary>
        /// 将列表中的记录组织成一个block
        /// </summary>
        /// <param name="eiInfo"></param>
        private void SubBlock(EIInfo eiInfo)
        {
            EIBlock subBlock = new EIBlock("result");
            subBlock.SetColumns(this.sub_grid.EIBlock.GetColumns());
            subBlock.SetRows(this.sub_grid.EIBlock.GetRows());
            eiInfo.AddBlock(subBlock);
        }

        /// <summary>
        /// “返回”按钮
        /// </summary>
        private void Return_Click(object sender, RoutedEventArgs e)
        {
            CmesWindows _window = this.Parent as CmesWindows;
            _window.DialogResult = false;
            _window.Close();
        }

        /// <summary>
        /// 根据物资编码的值，给其他文本框赋值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void fdMaterialCode_ValueChanged(object sender, ValueChangedEventArgs e)
        {
            if (e.NewValue == null && e.OldValue.Equals(""))
            {
                return;
            }

            EFDataField field = sender as EFDataField;
            CmesCustomView picker = field.Content as CmesCustomView;

            if (picker.ItemObject != null)
            {
                if (!picker.ItemObject.Equals(""))
                {
                    this.fdMaterialCode.Value = picker.ItemObject.GetType().GetProperty("fdMaterialCode").GetValue(picker.ItemObject, null) as string;
                    this.fdMaterialName.Value = picker.ItemObject.GetType().GetProperty("fdMaterialName").GetValue(picker.ItemObject, null) as string;
                    this.fdMetric.Value = picker.ItemObject.GetType().GetProperty("fdMetric").GetValue(picker.ItemObject, null) as string;
                    this.fdSpecModel.Value = picker.ItemObject.GetType().GetProperty("fdSpecModel").GetValue(picker.ItemObject, null) as string;
                    this.fdNumber.Value = picker.ItemObject.GetType().GetProperty("fdNumber").GetValue(picker.ItemObject, null) as string;
                    this.fdQuality.Value = picker.ItemObject.GetType().GetProperty("fdQuality").GetValue(picker.ItemObject, null) as string;

                    this.fdMaterialId.Value = picker.ItemObject.GetType().GetProperty("fdKeyId").GetValue(picker.ItemObject, null) as string;
                    this.fdMaterialInnerCode.Value = picker.ItemObject.GetType().GetProperty("fdMaterialInnerCode").GetValue(picker.ItemObject, null) as string;
                    this.fdMaterialType.Value = picker.ItemObject.GetType().GetProperty("fdMaterialType").GetValue(picker.ItemObject, null) as string;
                    this.fdPrice.Value = picker.ItemObject.GetType().GetProperty("fdPrice").GetValue(picker.ItemObject, null);
                    this.fdProvideDepartment.Value = picker.ItemObject.GetType().GetProperty("fdSupplyName").GetValue(picker.ItemObject, null);
                }
                //没选中时赋予空字符串
                else
                {
                    this.fdMaterialCode.Value = "";
                    this.fdMaterialName.Value = "";
                    this.fdMetric.Value = "";
                    this.fdSpecModel.Value = "";
                    this.fdNumber.Value = "";
                    this.fdQuality.Value = "";

                    this.fdMaterialId.Value = "";
                    this.fdMaterialInnerCode.Value = "";
                    this.fdMaterialType.Value = "";
                    this.fdPrice.Value = 0;
                    this.fdProvideDepartment.Value = "";
                }

            }
        }

        /// <summary>
        /// 实收金额等于实进数量乘以单价
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void fdPrice_ValueChanged(object sender, ValueChangedEventArgs e)
        {
            this.fdPrice.eRegex = @"^(\d{1,10})(\.\d{0,5})?$";
            this.fdPrice.eValidateErrorPrompt = "输入整数位不超过10位，小数位不超过5位的数字";
            if (this.fdPrice.Validate())
            {
                string fdPrice = String.IsNullOrEmpty(this.fdPrice.Value.ToString()) ? "0" : this.fdPrice.Value.ToString();
                string fdActualNumber = String.IsNullOrEmpty(this.fdActualNumber.Value.ToString()) ? "0" : this.fdActualNumber.Value.ToString();

                if (e.NewValue != null)
                {
                    if (this.fdPrice.Validate() && this.fdActualNumber.Validate())
                    {
                        this.fdSum.Value = Double.Parse(fdPrice) * Double.Parse(fdActualNumber);
                    }
                }
            }
        }

        /// <summary>
        /// 实收金额等于实进数量乘以单价
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void fdActualNumber_ValueChanged(object sender, ValueChangedEventArgs e)
        {
            this.fdActualNumber.eRegex = @"^(\d{1,10})(\.\d{0,5})?$";
            this.fdActualNumber.eValidateErrorPrompt = "输入整数位不超过10位，小数位不超过5位的数字";
            if (this.fdActualNumber.Validate())
            {
                string fdPrice = String.IsNullOrEmpty(this.fdPrice.Value.ToString()) ? "0" : this.fdPrice.Value.ToString();
                string fdActualNumber = String.IsNullOrEmpty(this.fdActualNumber.Value.ToString()) ? "0" : this.fdActualNumber.Value.ToString();

                if (e.NewValue != null)
                {
                    if (this.fdPrice.Validate() && this.fdActualNumber.Validate())
                    {
                        this.fdSum.Value = Double.Parse(fdPrice) * Double.Parse(fdActualNumber);
                    }
                }
            }
            
        }

        /// <summary>
        /// 入库时的判断
        /// </summary>
        /// <returns></returns>
        private bool ValidateImportType()
        {
            if (this.fdImportType.Value != null && "一般入库".Equals(this.fdImportType.Value.ToString()))
            {
                if (String.IsNullOrEmpty(this.fdInvoice.Value.ToString()) || String.IsNullOrEmpty(this.fdInvoiceSum.Value.ToString()))
                {
                    base.OpenEFWindowAlert("入库类型为一般入库时，则发票号、发票金额必须填写", true);
                    return false;
                }

                this.fdInvoiceSum.eRegex = @"^(\d{1,10})(\.\d{0,5})?$";
                this.fdInvoiceSum.eValidateErrorPrompt = "输入整数位不超过10位，小数位不超过5位的数字";
                if (!this.fdInvoiceSum.Validate())
                {
                    base.OpenEFWindowAlert("发票金额输入整数位不超过10位，小数位不超过5位的数字", true);
                    this.fdInvoiceSum.eRegex = "";
                    this.fdInvoiceSum.eValidateErrorPrompt = "";
                    return false;
                }
                this.fdInvoiceSum.eRegex = "";
                this.fdInvoiceSum.eValidateErrorPrompt = "";
            }

            return true;
        }

        private void ValidateCode()
        {
            EIInfo eiInfo = new EIInfo();
            eiInfo.Set("service", "ZMCMB2");
            eiInfo.Set("method", "validateCode");
            eiInfo.Set("fdNoteDate", this.fdNoteDate.Value);
            eiInfo.Set("fdNoteCode", this.fdNoteCode.Value);

            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(eiInfo, OnDoValidateCompleted);
        }

        /// <summary>
        /// 验证后的回调方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnDoValidateCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.GetStatus() != -1)
            {
                if (this.InsertGrid.ValidateField())
                {
                    string importType = this.fdImportType.Value.ToString();

                    //隐藏上帧页面
                    this.InsertGrid.Visibility = Visibility.Collapsed;//主表录入
                    this.Next.Visibility = Visibility.Collapsed;  //下一步按钮
                    this.Cancel.Visibility = Visibility.Collapsed; //关闭按钮

                    //展示下帧页面
                    this.RESULT.Visibility = Visibility.Visible;
                    this.DETAILS.Visibility = Visibility.Visible;

                    this.Save.Visibility = Visibility.Visible;
                    this.Clear.Visibility = Visibility.Visible;
                    this.Last.Visibility = Visibility.Visible;
                    this.Commit.Visibility = Visibility.Visible;
                    this.Return.Visibility = Visibility.Visible;

                    if (!importType.Equals("一般入库"))
                    {
                        this.fdPrice.IsReadOnly = false;
                        this.fdInvoice.IsReadOnly = true;
                        this.fdInvoiceSum.IsReadOnly = true;
                    }
                    else
                    {
                        this.fdPrice.IsReadOnly = true;
                        this.fdInvoice.IsReadOnly = false;
                        this.fdInvoiceSum.IsReadOnly = false;
                    }
                }
            }
            else
            {
                this.OnCommitMessagePopup(e.EIInfo);//操作失败，消息提醒
            }
        }
    }
}
